package cn.acyou.utils;

import cn.acyou.model.TransResult;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

/**
 * 开发者中心：
 * http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
 * 开发者文档：
 * http://api.fanyi.baidu.com/product/113
 *
 * @author youfang
 * @version [1.0.0, 2021-3-26]
 **/
public class TranslateUtil {

    public static final String Zh = "zh";
    public static final String En = "en";

    private static final String APP_ID = "20190808000324958";
    private static final String SECURITY_KEY = "2I7Z8KQQitJVt1mzn1fi";
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    public static String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpUtil.get(TRANS_API_HOST, params, null);
    }

    private static Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        params.put("sign", Md5Util.getMD5(src));

        return params;
    }

    public static void main(String[] args) {
        String query = "高度600米 长1200米 发发发";
        String transResult = getTransResult(query, "auto", "en");
        System.out.println(transResult);
        TransResult jsonStrToBean = JSON.parseObject(transResult, TransResult.class);
        System.out.println(jsonStrToBean);
    }



}
